package com.sduept.nwld.dataserver.controller.dataview.weather;

import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.manager.FaultRecordQueryManager;
import com.sduept.bigdata.weather.entity.HistoryTyphoon;
import com.sduept.bigdata.weather.entity.TyphoonFaultInfo;
import com.sduept.bigdata.weather.manager.HistoryTyphoonManager;
import com.sduept.bigdata.weather.manager.TyphoonFaultInfoManager;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.utils.DateUtil;
import com.sduept.utils.PingYinUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 故障设备和最近台风点关系信息维护
 * @date 2018-09-29
 */
@Named
@ViewScoped
public class TyphoonFaultInfoController extends AbstractController {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1290368403130262405L;
	
	@Autowired
	private SuperDAO superDao;
	@Autowired
	private HistoryTyphoonManager historyTyphoonManager;//历史台风
	@Autowired
	private TyphoonFaultInfoManager typhoonFaultInfoManager;//故障设备和最近台风点关系
	@Autowired
	private FaultRecordQueryManager faultRecordQueryManager;//故障

	private String filterTyphoon;//过滤查询
	private Map<String, List<String>> typhoonMap = new HashMap<String, List<String>>();
	private TreeNode root;
	private TreeNode currentSelect;//当前选择
	private HistoryTyphoon currentTyphoon = new HistoryTyphoon();//当前选择的历史台风
	private List<TyphoonFaultInfo> infoList = new ArrayList<TyphoonFaultInfo>();//故障和台风点关系信息列表
	private TyphoonFaultInfo selected = null;//当前选择
	private List<FaultRecord> faultList = new ArrayList<FaultRecord>();//故障列表
	private String equipment;//故障设备
	private Date startDate;//开始时间
	private Date endDate;//结束时间
	private List<FaultRecord> selectedFault = new ArrayList<FaultRecord>();//前台选择的故障
	
	@PostConstruct
	public void init() {
		
		initTyphoonPinYin();//初始化拼音检索
		initTyphoonTree();//初始化台风树
	}
	
	/**
	 * 初始化历史台风拼音检索数据
	 */
	public void initTyphoonPinYin(){
		
		List<HistoryTyphoon> typhoonList = superDao.findByCondition("tid is not null group by tid", null, HistoryTyphoon.class);
		for(HistoryTyphoon typhoon : typhoonList){
			
			if(StringUtils.isNotEmpty(typhoon.getTname())){
				
				String key = PingYinUtil.getPingYinHeader(typhoon.getTname());
				List<String> htl = typhoonMap.get(key);
				if(null == htl){//key不存在
					
					htl = new ArrayList<String>();
					typhoonMap.put(key, htl);
				}
				htl.add(typhoon.getTname());
			}
		}
	}
	
	/**
	 * 拼音检索历史台风
	 * @param query
	 * @return
	 */
	public List<String> completeTyphoon(String query){
		
		List<String> result = new ArrayList<String>();
		for(String key : typhoonMap.keySet()){
			
			if(key.startsWith(query)){
				result.addAll(typhoonMap.get(key));
			}
		}
		
		return result;
	}
	
	/**
	 * 自动补全
	 * @param event
	 */
	public void autoCompleteTyphoon(SelectEvent event){
		
		Object obj = event.getObject();
		if(null != obj){
			filterTree(obj.toString());
		}
	}
	
	/**
	 * 过滤台风树
	 * @param tname
	 */
	public void filterTree(String tname){
		
		root = new DefaultTreeNode();
		List<HistoryTyphoon> typhoonList = superDao.findByCondition(HistoryTyphoon.class, "tname = ? group by tid", tname);
		genTyphoonTreeNode(typhoonList);
	}
	
	/**
	 * 生成台风树
	 */
	public void initTyphoonTree(){

		filterTyphoon = "";//清空查询条件
		root = new DefaultTreeNode();
		List<HistoryTyphoon> typhoonList = superDao.findByCondition("tid is not null group by tid", null, "order by tid desc", null, HistoryTyphoon.class);
		genTyphoonTreeNode(typhoonList);
	}
	
	/**
	 * 生成台风树
	 */
	private void genTyphoonTreeNode(List<HistoryTyphoon> typhoonList){
		
		for(HistoryTyphoon typhoon : typhoonList){
			new LibTreeNode("typhoon", typhoon, root);
		}
	}
	
	/**
	 * 节点展开
	 * @param event
	 */
	public void onNodeExpand(NodeExpandEvent event) {
		
		TreeNode node =  event.getTreeNode();
		node.getChildren().clear();
		if("typhoon".equals(node.getType())){//台风节点
			
			HistoryTyphoon historyTyphoon = (HistoryTyphoon) node.getData();
			Object[] objs = new Object[1];
			objs[0] = historyTyphoon.getTid();
			List<HistoryTyphoon> typhoonList = superDao.findByCondition("tid = ?", objs, "order by updateTime desc", null, HistoryTyphoon.class);
			for(HistoryTyphoon typhoon : typhoonList){
				new LibTreeNode("typhoonObject", typhoon, node);
			}
		}
	}
	
	/**
	 * 节点选择
	 * @param event
	 */
	public void onNodeSelect(NodeSelectEvent event) {
		
		currentSelect =  event.getTreeNode();
		infoList.clear();
		selected = null;//清除选择
		currentTyphoon = new HistoryTyphoon();
		if("typhoonObject".equals(currentSelect.getType())){
			
			HistoryTyphoon historyTyphoon = (HistoryTyphoon) currentSelect.getData();
			try {
				BeanUtils.copyProperties(currentTyphoon, historyTyphoon);//克隆
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
			infoList = typhoonFaultInfoManager.findByTyphoonId(historyTyphoon.getId());
			
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(historyTyphoon.getUpdateTime());
			calendar.add(Calendar.DAY_OF_MONTH, -2);//前两天
			startDate = calendar.getTime();
			calendar.setTime(historyTyphoon.getUpdateTime());
			calendar.add(Calendar.DAY_OF_MONTH, +2);//后两天
			endDate = calendar.getTime();
			String startStr = DateUtil.getStringDate(startDate, DateUtil.pattern_ymd) + " 00:00:00";
			String endStr = DateUtil.getStringDate(endDate, DateUtil.pattern_ymd) + " 23:59:59";
			Date startTime = DateUtil.getDateByString(startStr, DateUtil.pattern_ymdhms);
			Date endTime = DateUtil.getDateByString(endStr, DateUtil.pattern_ymdhms);
			faultList = faultRecordQueryManager.findFaultByTime(startTime, endTime);//查询故障
		}
	}
	
	/**
	 * 搜索故障
	 */
	public void searchFault(){
		
		if((startDate.getTime() - endDate.getTime()) > 0){
			addErrorMessage("截止时间不能小于开始时间！");
		}else{
			
			String startStr = DateUtil.getStringDate(startDate, DateUtil.pattern_ymd) + " 00:00:00";
			String endStr = DateUtil.getStringDate(endDate, DateUtil.pattern_ymd) + " 23:59:59";
			Date startTime = DateUtil.getDateByString(startStr, DateUtil.pattern_ymdhms);
			Date endTime = DateUtil.getDateByString(endStr, DateUtil.pattern_ymdhms);
			//查询故障
			if(StringUtils.isEmpty(equipment)){
				faultList = faultRecordQueryManager.findFaultByTime(startTime, endTime);
			}else{
				faultList = faultRecordQueryManager.findFaultByTimeDeviceName(equipment, startTime, endTime);
			}
		}
	}
	
	/**
	 * 刷新故障
	 */
	public void refreshFault(){
		
		equipment = null;
		searchFault();
	}
	
	/**
	 * 故障台风信息选择
	 * @param event
	 */
	public void onRowSelect(SelectEvent event) {
		selected = (TyphoonFaultInfo) event.getObject();
	}
	
	/**
	 * 删除故障设备和台风点关系
	 */
	public void deleteInfo(){
		
		if(null != selected){
			
			typhoonFaultInfoManager.deleteInfoById(selected.getId());
			infoList = typhoonFaultInfoManager.findByTyphoonId(currentTyphoon.getId());//重置列表
			addSuccessMessage("删除成功！");
			selected = null;
		}else{
			addErrorMessage("请选择要删除的数据！");
		}
	}
	
	/**
	 * 保存故障设备和台风点关系
	 */
	public void saveInfo(){
		
		if(selectedFault.size() > 0){
			
			for(FaultRecord faultRecord : selectedFault){
				
				List<TyphoonFaultInfo> infoList = typhoonFaultInfoManager.findByFaultId(faultRecord.getId());
				if(infoList.size() == 0){
					typhoonFaultInfoManager.calculateTyphoonFaultInfo(faultRecord, currentTyphoon);
				}
			}
			infoList = typhoonFaultInfoManager.findByTyphoonId(currentTyphoon.getId());//重置列表
			selectedFault = new ArrayList<FaultRecord>();
			addSuccessMessage("给定故障设备和给定台风点关系信息保存成功！");
		}else{
			addErrorMessage("请选择故障信息！");
		}
	}
	
	public String getFilterTyphoon() {
		return filterTyphoon;
	}

	public void setFilterTyphoon(String filterTyphoon) {
		this.filterTyphoon = filterTyphoon;
	}

	public TreeNode getRoot() {
		return root;
	}

	public void setRoot(TreeNode root) {
		this.root = root;
	}

	public TreeNode getCurrentSelect() {
		return currentSelect;
	}

	public void setCurrentSelect(TreeNode currentSelect) {
		this.currentSelect = currentSelect;
	}

	public HistoryTyphoon getCurrentTyphoon() {
		return currentTyphoon;
	}

	public void setCurrentTyphoon(HistoryTyphoon currentTyphoon) {
		this.currentTyphoon = currentTyphoon;
	}

	public List<TyphoonFaultInfo> getInfoList() {
		return infoList;
	}

	public void setInfoList(List<TyphoonFaultInfo> infoList) {
		this.infoList = infoList;
	}

	public TyphoonFaultInfo getSelected() {
		return selected;
	}

	public void setSelected(TyphoonFaultInfo selected) {
		this.selected = selected;
	}

	public List<FaultRecord> getFaultList() {
		return faultList;
	}

	public void setFaultList(List<FaultRecord> faultList) {
		this.faultList = faultList;
	}

	public String getEquipment() {
		return equipment;
	}

	public void setEquipment(String equipment) {
		this.equipment = equipment;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public List<FaultRecord> getSelectedFault() {
		return selectedFault;
	}

	public void setSelectedFault(List<FaultRecord> selectedFault) {
		this.selectedFault = selectedFault;
	}

}
